# -*- coding: utf-8 -*-
# @File:     upload_params_images.py
# @Author:
# @DateTime: 2025/06/06/9:51

from typing import Optional, Union, Any

from fastapi.encoders import jsonable_encoder
from sqlalchemy import or_
from sqlalchemy.orm import Session
from app.db.database import get_db
from app.models.system import Users
from app.utils import security
from app.utils.custom_response import success_response
from fastapi import APIRouter, Query, Body, Path, Depends, UploadFile, Form, File, Request
from pydantic import BaseModel, Field

from app.models.generate import GenerateParamImage
from app.utils.curd_base import ModelCRUD
from app.utils.file_storage import get_storage_file, save_storage_file, delete_storage_file

router = APIRouter()


class CRUDGenerateParamImage(ModelCRUD):

    model = GenerateParamImage

    @staticmethod
    def serializer(queryset, only: tuple = (), date_format: str = None, datetime_format: str = None,
                   time_format: str = None):
        li = list()
        for instance in queryset:
            data = instance.to_dict(only=only, date_format=date_format, datetime_format=datetime_format, time_format=time_format)
            data['path_url'] = get_storage_file(data.get('path')) if data.get('path') else None
            li.append(data)
        return li


class CreateGenerateParamImage(BaseModel):
    user_id: int = Field(description='用户')
    task_id: Optional[int] = Field(default=None, description='任务')
    record_id: Optional[int] = Field(default=None, description='记录')
    path: str = Field(description='文件')
    file_type: str = Field(description='文件类型')


class ResGenerateParamImage(CreateGenerateParamImage):
    path_url: Optional[str] = Field(default=None, description='url')


class DeleteModel(BaseModel):
    id: list[int] = Field(description='ID列表')


@router.post("/param_image", summary="上传参数图", response_model=ResGenerateParamImage, name='上传参数图')
async def param_image(
    *,
    db: Session = Depends(get_db),
    file: UploadFile = File(...),
    current_user: Users = Depends(security.verify_access_token),
) -> Any:

    path, file_type = save_storage_file(file, folder='generate/params')

    req_data = {
        'user_id': current_user.id,
        'path': path,
        'file_type': file_type,
    }
    crud = CRUDGenerateParamImage()
    instance = crud.create(db, data=CreateGenerateParamImage.model_validate(req_data))
    only = ('id', 'path', 'file_type')
    data = instance.to_dict(only=only)
    data['path_url'] = get_storage_file(data.get('path')) if data.get('path') else None
    return success_response(data=data)


user_able_filter_list = [
    {'name': 'user_id', 'source_filed': 'user_id', 'lookup_expr': 'eq', 'label': 'userID', 'type': str, 'method': None, 'required': True},
]


@router.get("/param_image", summary="获取参数图", response_model=ResGenerateParamImage, name='获取参数图')
async def param_image(
    *,
    db: Session = Depends(get_db),
    page: int = Query(1, description='页码', ge=1),
    page_size: int = Query(10, description='页面大小', le=50, ge=1),
    current_user: Users = Depends(security.verify_access_token),
) -> Any:
    order_by_fields = ('-id',)
    crud = CRUDGenerateParamImage()
    req_data = {
        'user_id': current_user.id
    }
    queryset, total = crud.get_page_queryset(db, page=page, page_size=page_size, req_data=req_data, able_filter_list=user_able_filter_list, order_by_fields=order_by_fields)
    only = ('id', 'path', 'file_type')
    items = crud.serializer(queryset, only=only)
    resp = {
        "list": items,
        'total': total
    }
    return success_response(data=resp)





